package softswitch.service;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import softswitch.model.Plan;


@Stateless
public class PlanDAO {

	
	@PersistenceContext(unitName = "persistence")
    private EntityManager em;
	
	
	public Plan getById(Integer id){	
		return em.find(Plan.class, id);
	}
	    
    public Plan save(Plan plan) {
    	em.persist(plan); 
    	return plan;
    }
    
    public Plan update(Plan plan) {
    	return em.merge(plan);
    }
    
    public void delete(Integer id) {
    	em.remove(em.find(Plan.class, id));	
    }
    
	@SuppressWarnings("unchecked")
    public List<Plan> list(int first, int max) {    	
    	Query query = em.createQuery("SELECT e FROM Plan e");
    	if (max > 0) {
            query.setMaxResults(max);
        }
    	if (first > 0) {
            query.setFirstResult(first);
        }
        return query.getResultList();   
    }
	
	public Plan getByCode(Integer code) {
		Plan result = null;
    	Query query = em.createQuery("SELECT e FROM Plan e WHERE e.code=:code");
    	query.setParameter("code", code);
		try {
			result = (Plan) query.getSingleResult(); 
        }
    	catch (Exception e) {
		}
        return result; 
	}
	
	
}

